package com.pangolin.pangolinim.service;


import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;

import com.orhanobut.logger.Logger;
import com.pangolin.pangolinim.app.BroadcastMsg;
import com.pangolin.pangolinim.app.mainApp;
import com.pangolin.pangolinim.service.system.AppRuntime;
import com.pangolin.pangolinim.service.thread.base.baseThread;
import com.pangolin.pangolinim.service.thread.recvThread;
import com.pangolin.pangolinim.service.thread.sendThread;
import com.pangolin.pangolinim.service.thread.socketThread;
import com.pangolin.pangolinim.utils.BundleUtil;
import com.pangolin.pangolinim.utils.SPUtil;


/**
    @ CoreService类
    @ TODO:核心服务类，主要负责和后台服务器进行通信，并将通讯结果通过广播形式交换给上层UI
 */

public class CoreService extends Service {
    private CoreMsgReceiver receiver;
    private IntentFilter intentFilter;

    private socketThread socket_thread;
    private sendThread send_thread;
    private recvThread recv_thread;

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Logger.d("onCreate processID : %d" , android.os.Process.myPid());

        /** step1 - 注册广播接收器 */
        intentFilter = new IntentFilter();
        intentFilter.addAction(BroadcastMsg.CORE_ACTION);
        receiver = new CoreMsgReceiver();
        registerReceiver(receiver , intentFilter);
        /** step2 - 初始化系统配置 */
        AppRuntime.setHost(mainApp.getChatHost());
        AppRuntime.setPort(mainApp.getChatPort());
        AppRuntime.setFileHost(mainApp.getFileServer());
        AppRuntime.setIsNotify((boolean) SPUtil.get(this , "globle_notify" , true));
        /** step3 - 链接服务器 */
        socket_thread = new socketThread(socketThread.CONNECT);
        socket_thread.start();
        try {
            socket_thread.join();//等待连接线程结束
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        /** setp4 - 开启发送和接收线程 */
        send_thread = new sendThread();
        recv_thread = new recvThread();
        send_thread.start();
        recv_thread.start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Logger.d("onStartCommand");
        //通知上层UI当前服务状态
        BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_CORE_SERVSTARED , "");
        Intent intent1 = new Intent(BroadcastMsg.ACTIVITY_ACTION);
        intent1.putExtras(bundleUtil.getBundle());
        mainApp.getContext().sendBroadcast(intent1);

        return super.onStartCommand(intent, flags, startId);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Logger.d("onDestroy");
        //发送服务成功结束消息给UI
        BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_CORE_SERVSTOPED , "");
        Intent intent = new Intent(BroadcastMsg.ACTIVITY_ACTION);
        intent.putExtras(bundleUtil.getBundle());
        mainApp.getContext().sendBroadcast(intent);

        //注销广播接收器
        if(receiver != null){
            unregisterReceiver(receiver);
        }
        android.os.Process.killProcess(android.os.Process.myPid());
    }


    /**
        @ CoreMsgReceiver类
        @ TODO: 主要的广播信息交换类，负责处理和上层UI广播通讯
     */
    public class CoreMsgReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(final Context context , Intent intent){
            Bundle bundle = intent.getExtras();
            BundleUtil bundleUtil = new BundleUtil(bundle);

            switch (bundleUtil.getType()){
                case BroadcastMsg.SIG_UI_STOP:
                    //断开服务器连接（recv线程会自动退出）
                    socket_thread = new socketThread(socketThread.DISCONNECT);
                    socket_thread.start();
                    //关闭发送线程消息循环
                    if(send_thread != null){
                        Message msg = new Message();
                        msg.what = BroadcastMsg.SIG_UI_STOP;
                        send_thread.getHandler().sendMessage(msg);
                    }
                    //等待线程退出后通知UI关闭服务
                    try {
                        socket_thread.join();
                        send_thread.join();
                        recv_thread.join();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    BundleUtil bundleSend = new BundleUtil(BroadcastMsg.SIG_CORE_THREADEND , "");
                    Intent intentSend = new Intent(BroadcastMsg.ACTIVITY_ACTION);
                    intentSend.putExtras(bundleSend.getBundle());
                    mainApp.getContext().sendBroadcast(intentSend);
                    break;
                case BroadcastMsg.SIG_UI_DATA:
                    if(send_thread != null){
                        Message msg = new Message();
                        msg.what = BroadcastMsg.SIG_UI_DATA;
                        msg.obj = bundleUtil.getData();
                        send_thread.getHandler().sendMessage(msg);
                    }
                    break;
                default:
            }
        }
    }
}